﻿
Namespace storageJobConsumerInternal
    Partial Public Class diskslice(Of ATOM_T As atom)
        Protected Structure diskoper
            Private Shared ReadOnly def As Int64 = 0
            Private Shared ReadOnly inv As Int64 = npos
            Private cs As String
            Private startMs As Int64

            Shared Sub New()
                assert([default](Of Int64)() = def)
            End Sub

            Public Sub start()
                If needtrace Then
                    cs = callingcode(1)
                End If
                assert(startMs = def)
                startMs = Now.milliseconds()
            End Sub

            Public Sub [end](ByRef duration As Int64)
                assert(startMs <> def AndAlso startMs <> inv)
                duration = Now.milliseconds() - startMs
                startMs = inv
            End Sub

            Protected Overrides Sub Finalize()
                assert(startMs = inv, cs)
            End Sub
        End Structure
    End Class

    Public Class atom
        Private _start As UInt64 = 0
        Public Property start As UInt64
            Get
                Return _start
            End Get
            Private Set(ByVal value As UInt64)
                _start = value
            End Set
        End Property

        Private ReadOnly _metaLength As UInt64 = 0
        Public Function metaLength() As UInt64
            Return _metaLength
        End Function

        Private ReadOnly _length As UInt64 = 0
        Public Function length() As UInt64
            Return _length
        End Function

        Public Function metaStart() As UInt64
            Return start() + keylength()
        End Function

        Public Function keylength() As UInt64
            Return length() - metaLength()
        End Function

        Public Function [end]() As UInt64
            Return start() + length()
        End Function

        Private Sub move(ByVal offset As Int64)
            start += offset
        End Sub

        Public Sub forward(ByVal offset As UInt64)
            Try
                move(offset)
            Catch ex As Exception
                assert(False, ex.Message)
            End Try
        End Sub

        Public Sub backward(ByVal offset As UInt64)
            Try
                move(-offset)
            Catch ex As Exception
                assert(False, ex.Message)
            End Try
        End Sub

        Public Sub New(ByVal start As UInt64, ByVal metaStart As UInt64, ByVal metaLength As UInt64)
            assert(metaStart > start)
            Me.start() = start
            Me._metaLength = metaLength
            Me._length = metaStart - start + metaLength
        End Sub

        Public Overridable Function read(ByVal meta As bytes) As Boolean
            Return assert(False)
        End Function
    End Class
End Namespace
